<?php
namespace app\admin\controller;

use think\Controller;

class Qrcode extends Controller
{
    //检查是否登录
    public function initialize()
    {
        if (!session('admin')) {
            $this->error('请先登录！', url('/admin/login/login'));
        }
    }
    
    public function index()
    {
        $list = DB("qrcode")->alias('q')
        ->leftJoin("huabo_sell h", "h.qr_id=q.id")
        ->leftJoin("sell_user u", "h.sell_id=u.id")
        ->where("huabo_status=0")
        ->field("q.*,u.name")
        ->paginate(20);
        
        $this->assign('list', $list);
        return $this->fetch('index');
    }


    //批量生成二维码
    public function piliang(){
        if($_POST){
            $num = $_POST['number'];
            for($i=0; $i<$num; $i++){
                $code = "Q".time().$i;
                $result = DB("qrcode")->insert(['num' => $code,'create_time' =>time()]);
            }
            if($result){
                $this->success();
            } else {
                $this->error();
            }
        } else {
            return $this->fetch();
        }
    }

    //划拨
    public function huabo(){
        if($_POST){
            $num = $_POST['number'];
            $sell = DB("sell_user")->find($_POST['sell']);
            $str = "";
            //划拨
            $qrlist = DB("qrcode")->where(['huabo_status' => 0])->limit($num)->select();
            foreach($qrlist as $key => $qr){
                $str .= $qr['id'].",";
                //划拨给商户
                $result = DB("huabo_sell")->insert(['qr_id' => $qr['id'],'sell_id' =>$sell['id'],'status' => 0,'create_time' => time()]);
            }
            //添加划拨记录
            $result1 = DB("huabo_logs")->insert(['logs' => "管理员于".date("Y-m-d H:i:s")."划拨给【".$sell['name'] . "】【".count($qrlist)."】个二维码",'qr_ids' =>$str,"sell_id" => $sell['id'],'create_time' => time()]);
            //
            if($result && $result1){
                $this->success();
            } else {
                $this->error();
            }
        } else {
            $this->assign("sell", DB("sell_user")->where(['status' => 1])->select());
            return $this->fetch();
        }
    }

    

    
}
